// 对话历史管理
let conversationHistory = [];
let currentConversationId = generateId();

// DOM元素
const chatContainer = document.getElementById('chat-container');
const userInput = document.getElementById('user-input');
const sendButton = document.getElementById('send-button');
const historySidebar = document.getElementById('history-sidebar');
const historyList = document.getElementById('history-list');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadHistory();
    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 发送消息
async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;

    // 添加用户消息到界面
    addMessage('user', message);
    userInput.value = '';

    // 显示"正在输入"指示器
    const typingIndicator = showTypingIndicator();

    try {
        // 这里模拟流式响应，实际应用中替换为真实的API调用
        const response = await mockStreamingResponse(message);

        // 移除"正在输入"指示器
        chatContainer.removeChild(typingIndicator);

        // 添加助手响应到界面
        // addMessage('assistant', response);

        // 保存到当前对话历史
        saveToCurrentConversation(message, response);
    } catch (error) {
        console.error('Error:', error);
        chatContainer.removeChild(typingIndicator);
        addMessage('assistant', '抱歉，发生了一个错误。请稍后再试。');
    }
}

// 模拟流式响应
async function mockStreamingResponse(message) {
    // 实际应用中，这里应该是fetch或WebSocket连接
    // 以下是模拟实现

    // const responses = [
    //     "这是一个模拟的流式响应。",
    //     "我正在逐步生成回答内容。",
    //     "首先，我会分析你的问题...",
    //     "然后，我会组织语言进行回答...",
    //     "最后，我会提供一个完整的回复。"
    // ];
    let fullResponse = '';
    addMessage('assistant', '');

    const response = await fetch(`http://localhost:8100/chat?mes=${message}`);
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const text = decoder.decode(value);
        // console.log('Received:', text);
        // 处理数据
        fullResponse+=text
        updateLastMessage('assistant', fullResponse);

    }

    return fullResponse;
}

// 实际API调用示例（使用fetch）
async function fetchStreamingResponse(message) {
    // 实际API端点
    const response = await fetch('https://api.example.com/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            message: message,
            conversation_id: currentConversationId
        })
    });

    if (!response.ok) {
        throw new Error('Network response was not ok');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantMessage = '';

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        assistantMessage += chunk;

        // 更新最后一条消息（助手的消息）
        updateLastMessage('assistant', assistantMessage);
    }

    return assistantMessage;
}

// 添加消息到聊天界面
function addMessage(role, content) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    messageDiv.textContent = content;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;

    // 如果是用户消息，保存到当前对话历史
    if (role === 'user') {
        if (!conversationHistory.find(c => c.id === currentConversationId)) {
            conversationHistory.push({
                id: currentConversationId,
                title: content.slice(0, 30),
                messages: []
            });
        }
    }
}

// 更新最后一条消息（用于流式输出）
function updateLastMessage(role, content) {
    const messages = document.querySelectorAll('.message');
    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        if (lastMessage.classList.contains(`${role}-message`)) {
            lastMessage.textContent = content;
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }
}

// 显示"正在输入"指示器
function showTypingIndicator() {
    const indicator = document.createElement('div');
    indicator.className = 'typing-indicator';
    indicator.innerHTML = `
        <span class="dot"></span>
        <span class="dot"></span>
        <span class="dot"></span>
    `;
    chatContainer.appendChild(indicator);
    chatContainer.scrollTop = chatContainer.scrollHeight;
    return indicator;
}

// 保存到当前对话历史
function saveToCurrentConversation(userMessage, assistantMessage) {
    const conversation = conversationHistory.find(c => c.id === currentConversationId);
    if (conversation) {
        conversation.messages.push({
            role: 'user',
            content: userMessage
        });
        conversation.messages.push({
            role: 'assistant',
            content: assistantMessage
        });

        // 更新本地存储
        saveHistory();
    }
}

// 保存历史到本地存储
function saveHistory() {
    localStorage.setItem('chatHistory', JSON.stringify(conversationHistory));
}

// 从本地存储加载历史
function loadHistory() {
    const savedHistory = localStorage.getItem('chatHistory');
    if (savedHistory) {
        conversationHistory = JSON.parse(savedHistory);
        renderHistoryList();
    }
}

// 渲染历史列表
function renderHistoryList() {
    historyList.innerHTML = '';
    conversationHistory.forEach(conversation => {
        const item = document.createElement('div');
        item.className = 'history-item';
        item.textContent = conversation.title;
        item.onclick = () => loadConversation(conversation.id);
        historyList.appendChild(item);
    });
}

// 加载特定对话
function loadConversation(conversationId) {
    const conversation = conversationHistory.find(c => c.id === conversationId);
    if (conversation) {
        currentConversationId = conversationId;
        chatContainer.innerHTML = '';
        conversation.messages.forEach(msg => {
            addMessage(msg.role, msg.content);
        });
        toggleHistory(); // 关闭侧边栏
    }
}

// 开始新对话
function startNewConversation() {
    currentConversationId = generateId();
    chatContainer.innerHTML = '';
}

// 切换历史侧边栏
function toggleHistory() {
    historySidebar.classList.toggle('visible');
}

// 导出历史记录（可选功能）
function exportHistory() {
    const dataStr = JSON.stringify(conversationHistory, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);

    const exportFileDefaultName = `chat-history-${new Date().toISOString()}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
}